package com.hnu.store.service.impl;

import com.hnu.store.entity.SearchRecord;
import com.hnu.store.entity.User;
import com.hnu.store.mapper.SearchRecordMapper;
import com.hnu.store.mapper.UserMapper;
import com.hnu.store.service.ISearchRecordService;
import com.hnu.store.service.ex.GetSearchRecordException;
import com.hnu.store.service.ex.SearchRecordDeleteException;
import com.hnu.store.service.ex.SearchRecordInsertException;
import java.util.ArrayList;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SearchRecordServiceImpl implements ISearchRecordService {

    @Autowired
    private SearchRecordMapper searchRecordMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    public void addSearchRecord(SearchRecord searchRecord) {
        Date date = new Date();
        searchRecord.setTime(String.valueOf(date));
        searchRecord.setCreatedTime(date);
        searchRecord.setModifiedTime(date);
        Integer userId = searchRecord.getUserId();
        //通过用户id找到用户名
        User user = userMapper.findById(userId);
        searchRecord.setCreatedUser(user.getUsername());
        searchRecord.setModifiedUser(user.getUsername());

        SearchRecord judgeRecord = searchRecordMapper.findSameRecord(searchRecord);
        //如果同一用户搜索同一文本，删除前一个记录
        if (judgeRecord == searchRecord){
            Integer rows = searchRecordMapper.deleteRecord(judgeRecord);
            /*
            如果rows！=1代表删除失败，爆出异常
            */
            if (rows != 1){
                throw new SearchRecordDeleteException("删除搜索记录过程中出现异常");
            }
        }
        Integer rows = searchRecordMapper.insertRecord(searchRecord);
        /*
        如果rows！=1代表插入失败，爆出异常
         */
       if (rows != 1) {
           throw new SearchRecordInsertException("插入搜索记录过程中出现异常");
       }

    }

    @Override
    public void deleteSearchRecord(SearchRecord searchRecord) {
        Integer rows = searchRecordMapper.deleteRecord(searchRecord);
        /*
        如果rows！=1代表删除失败，爆出异常
         */
        if (rows != 1){
            throw new SearchRecordDeleteException("删除搜索记录过程中出现异常");
        }
    }

    @Override
    public ArrayList<SearchRecord> getSearchRecord() {
        ArrayList<SearchRecord> searchRecords = searchRecordMapper.getSearchRecord();
        if (searchRecords ==null){
            throw new GetSearchRecordException("获取搜索记录过程中出现异常");
        }
        return searchRecords;
    }


}
